package com.studyroom.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.studyroom.dto.ChatMessage;
import com.studyroom.dto.Mail;
import com.studyroom.dto.Result;
import com.studyroom.dto.UserDTO;
import com.studyroom.entity.ChatFile;
import com.studyroom.mapper.ChatFileMapper;
import com.studyroom.mapper.UserMapper;
import com.studyroom.service.ChatService;
import com.studyroom.service.MailService;
import com.studyroom.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;

import static com.studyroom.utils.RabbitMqContants.EXCHANGE_TOPIC;
import static com.studyroom.utils.RedisContants.CHAT_SOLO_KEY;

@Service
@Slf4j
public class ChatServiceImpl implements ChatService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private AmqpTemplate amqpTemplate;
    @Resource
    private MailService mailService;
    @Resource
    private ChatFileMapper chatFileMapper;
    @Override
    public Result receiveSolo(Long id) {
        UserDTO me= UserHolder.getUser ();
        Long relationKey=userMapper.getUserRelationKey (me.getId (),id);
        String chatSoloKey=CHAT_SOLO_KEY+relationKey;
        List<String> chatMessageJsonList=stringRedisTemplate.opsForList ().range (chatSoloKey,0,-1);
        List<ChatMessage> chatMessageList=new LinkedList<> ();
        for(String chatMessageJson:chatMessageJsonList){
            chatMessageList.add (JSONUtil.toBean (chatMessageJson,ChatMessage.class));
        }
        return Result.ok (chatMessageList);
    }

    @Override
    public Result sendSole(ChatMessage chatMessage) {
        UserDTO me=UserHolder.getUser ();
        if(StrUtil.isBlank (chatMessage.getContent ())){
            return Result.fail ("输入消息不能为空");
        }
        if(chatMessage.getSender ()!=me.getId ()){
            return Result.fail ("无权发送消息");
        }
        if(chatMessage.getReceiver ()==null||chatMessage.getReceiver ()<1){
            return Result.fail ("找不到发送目标");
        }
        Long relationKey=userMapper.getUserRelationKey (me.getId (),chatMessage.getReceiver ());
        if(relationKey==null||relationKey<1){
            return Result.fail ("你还不是对方的好友");
        }
        chatMessage.setId (relationKey);
        chatMessage.setCreated (LocalDateTime.now ());
        chatMessage.setType (0);
        amqpTemplate.convertAndSend (EXCHANGE_TOPIC,"chat.solo",JSONUtil.toJsonStr (chatMessage).getBytes(StandardCharsets.UTF_8));
        //发送邮件告知对方
        Mail mail=new Mail ();
        mail.setSender (me.getId ());
        mail.setReceiver (chatMessage.getReceiver ());
        mail.setCreated (LocalDateTime.now ());
        String content= "您的好友"+me.getUsername ()+"向你发来了聊天消息";
        mail.setContent (content);

        mailService.send (mail);
        return Result.ok ();
    }

    @Override
    public Result uploadFile(MultipartFile file,Long sender,Long recever) {
        UserDTO me=UserHolder.getUser ();
        Long relationKey= userMapper.getUserRelationKey (sender,recever);
        if(relationKey<=0){
            return Result.fail ("对方不是你的好友");
        }
        try {
            ChatFile chatFile = new ChatFile ();
            long fileId = RandomUtil.randomLong (100000000L,999999999L);;
            chatFile.setId (fileId);
            chatFile.setName (file.getOriginalFilename ());
            chatFile.setData (file.getBytes ());
            int count = chatFileMapper.insert (chatFile);
            if(count<=0){
                return Result.fail ("文件发送失败");
            }
            ChatMessage chatMessage=new ChatMessage ();
            chatMessage.setId (relationKey);
            chatMessage.setSender (sender);
            chatMessage.setReceiver (recever);
            chatMessage.setFileId (fileId);
            chatMessage.setType (1);
            chatMessage.setContent (file.getOriginalFilename ());
            chatMessage.setCreated (LocalDateTime.now ());
            amqpTemplate.convertAndSend (EXCHANGE_TOPIC,"chat.solo",JSONUtil.toJsonStr (chatMessage).getBytes(StandardCharsets.UTF_8));

            //发送邮件告知对方
            Mail mail=new Mail ();
            mail.setSender (me.getId ());
            mail.setReceiver (chatMessage.getReceiver ());
            mail.setCreated (LocalDateTime.now ());
            String content= "您的好友"+me.getUsername ()+"向你发送了一个文件";
            mail.setContent (content);

            mailService.send (mail);
        }catch (Exception e){
            e.printStackTrace ();
            return Result.fail ("文件发送失败");
        }
        return Result.ok ();
    }

    @Override
    public ChatFile downloadFile(Long fileId) {
        ChatFile chatFile = chatFileMapper.selectById (fileId);
        return chatFile;
    }

}
